/*--- 触摸插件 ---*/
(function(window,document){

	//drag 函数表达式
	var drag = function(){
		this._target = null;
		//支持的事件类型
		this.events = ['dragstart','draging','dragend'];
		//事件对象
		this._events = {};
		//初始化
		this.init();
	};
	
	drag.fn = drag.prototype = {
		constructor:drag
		//范围选择
		,userselect:function(flag){
			//启用选择
			if(flag){
				document.body.onselectstart = null;
			//禁用选择
			}else{
				document.body.onselectstart = function(){
					return false;
				}
			}
		}
		//获取符合要求的元素 - 可能点击的是拖放元素的子元素，但是也要把父元素找到，赋值给 this._target
		,getTarget:function(target){
			do{
				if(/\bdraggable\b/.test(target.className)){
					this._target = target;
					return target;	
				}else{
					target = target.parentNode;	
				}
			}while(target.parentNode);
			return null;
		}
		,init:function(){
			var _t = this,sx,sy,disX,disy,clientX,clientY;
			//鼠标下按 - 其它操作 [ 添加禁用用户选择样式 ]
			document.addEventListener('mousedown',function(e){
				//初始化 _target 对象
				_t.getTarget(e.target);
				if(_t._target === null) return;
				//存在 - 禁用用户选择
				_t.userselect(false);
				_t.trigger(_t._events.dragstart,{
					target:_t._target,
					sx:e.clientX,
					sy:e.clientY,
					clientX:e.clientX,
					clientY:e.clientY,
					type:'dragstart',
					originalEvent:e
				});
			});
			//鼠标移动
			document.addEventListener('mousemove',function(e){
				if(_t._target === null) return;
				_t.trigger(_t._events.draging,{
					target:_t._target,
					sx:sx,
					sy:sx,
					clientX:e.clientX,
					clientY:e.clientY,
					type:'draging',
					originalEvent:e
				});
			});
			//鼠标弹起 - 
			document.addEventListener('mouseup',function(e){
				if(_t._target === null) return;
				//无论如何启用选择
				_t.userselect(true);
				_t.trigger(_t._events.dragend,{
					target:_t._target,
					sx:sx,
					sy:sx,
					clientX:e.clientX,
					clientY:e.clientY,
					type:'dragend',
					originalEvent:e
				});
				//置空
				_t._target = null;
			});
		}
		//事件绑定
		,on:function(evts,hdr){
			var evtArr = evts.split(' '),
				i = 0,
				len = evtArr.length,
				isFunc = typeof hdr == 'function',
				type;
			for(;i < len;i++){
				type = evtArr[i];
				this._events[type] = this._events[type] || [];
				if(isFunc){
					this._events[type].push(hdr);
				}
			}
			return this;
		}
		//事件触发
		,trigger:function(evt,e){
			
			if(!!evt){
				for(var i = 0,len = evt.length;i < len;i++){
					evt[i].call(this,e);	
				}
			}
		}
		//事件卸载
		,off:function(evts,hdr){
			var evtArr = evts.split(' '),
				i = evtArr.length,
				type;
			for(;i > 0;i--){
				type = evtArr[i];
				if(this._events[type] instanceof Array){
					for(j = this._events[type].length;j > 0;j--){
						//删除对应函数
						hdr == this._events[type][j] && this._events[type].splice(j,1);
					}
				}
			}
			return this;
		}
	};
	
	//将实例化的拖拽对象赋值给 window 对象
	window.drag = new drag();
})(window,document);